package com.mjf.thread;

/**
 * 使用 Runnable 接口的方式实现多线程
 */
public class ThreadSync02 {

    public static void main(String[] args) {

        // 创建售票对象
        Ticket02 ticket = new Ticket02();

        Thread aa = new Thread(ticket);
        aa.setName("AA");
        aa.start();

        // 创建BB线程
        Thread bb = new Thread(ticket);
        bb.setName("BB");
        bb.start();

        // 创建CC线程
        Thread cc = new Thread(ticket);
        cc.setName("CC");
        cc.start();

    }
}


class Ticket02 implements Runnable {
    private static int number = 100;
    private Boolean loop = true;

    @Override
    public void run() {
        while (loop) {
//            sale(); // 会超卖
//            syncSale(); // 正常售卖
//            staticSyncSale(); // 正常售卖

/*            synchronized (this) {
                sale(); // 正常售卖
            }*/

            synchronized (Ticket.class) {
                sale(); // 正常售卖
            }

            if(number <= 0) {
                loop = false;
            }
        }
    }

    // 静态同步方法：静态同步方法的默认锁是当前类.class
    public static synchronized void staticSyncSale() {
        if (number > 0) {
            try {
                Thread.sleep(50);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            number--;
            System.out.println(Thread.currentThread().getName() + "卖出第：\t" + (100 - number) + "\t 还剩下：" + number);
        }
    }

    // 非静态同步方法：非静态同步方法的默认锁是this（对于不用的对象无法达到同步的效果）
    public synchronized void syncSale() {
        if (number > 0) {
            try {
                Thread.sleep(50);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            number--;
            System.out.println(Thread.currentThread().getName() + "卖出第：\t" + (100 - number) + "\t 还剩下：" + number);
        }
    }

    // 普通方法
    public void sale() {
        if (number > 0) {
            try {
                Thread.sleep(50);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            number--;
            System.out.println(Thread.currentThread().getName() + "卖出第：\t" + (100 - number) + "\t 还剩下：" + number);
        }
    }

}
